package org.jflame.commons.json.jackson;

import org.jflame.commons.model.pair.IIntKeyPair;
import org.jflame.commons.model.pair.KeyValuePair;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;

public class IntKeyPairEnumCustomized {

    /**
     * IntKeyPair自定义序列化,只输出key值
     * 
     * @author charles.zhang
     */
    public static class IntKeyPairUsingKeySerializer extends JsonSerializer<IIntKeyPair> {

        @Override
        public void serialize(IIntKeyPair value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
            if (value == null) {
                gen.writeNull();
            } else {
                gen.writeNumber(value.getKey());
            }
        }

    }

    /**
     * 实现了IntKeyPair接口的枚举类的自定义反序列化. 通过key值生成相应枚举类
     * 
     * @author charles.zhang
     */
    public static class IntKeyPairEnumDeserializer<T extends Enum<T> & IIntKeyPair> extends StdDeserializer<T> {

        private static final long serialVersionUID = -1640122389932986565L;

        protected IntKeyPairEnumDeserializer(Class<?> vc) {
            super(vc);
            if (!IIntKeyPair.class.isAssignableFrom(vc)) {
                throw new IllegalArgumentException(
                        "Type mismacth," + vc.getName() + " not implement interface IIntKeyPair");
            }
        }

        @Override
        public T deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
            Integer intVal = p.getValueAsInt();

            Object[] enums = handledType().getEnumConstants();
            if (enums == null) {
                throw new JsonParseException(p, "Type mismacth, '" + handledType().getName() + "' not an enum class");
            }
            return KeyValuePair.getEnumByKey((Class<T>) _valueClass, intVal);

        }
    }
}
